package com.heipi.myjavademo.布隆过滤器;

import java.util.BitSet;

/**
 * @author: honry.guan
 * @create: 2025-08-01 15:55
 **/
public class MyBloomFilter {

    static class SimpleBloomFilter {
        private final BitSet bitSet;
        private final int[] hashSeeds;
        private final int capacity;

        public SimpleBloomFilter(int capacity, int hashCount) {
            this.capacity = capacity;
            this.bitSet = new BitSet(capacity);
            this.hashSeeds = new int[hashCount];
            // 简单的哈希种子
            for (int i = 0; i < hashCount; i++) {
                hashSeeds[i] = i * 2 + 1;
            }
        }

        public void add(String item) {
            for (int seed : hashSeeds) {
                int hash = Math.abs((item.hashCode() * seed) % capacity);
                bitSet.set(hash);
            }
        }

        public boolean mightContain(String item) {
            for (int seed : hashSeeds) {
                int hash = Math.abs((item.hashCode() * seed) % capacity);
                if (!bitSet.get(hash)) {
                    return false;
                }
            }
            return true;
        }
    }

    public static void main(String[] args) {
        // 创建布隆过滤器
        SimpleBloomFilter bloomFilter = new SimpleBloomFilter(1000, 3);
        bloomFilter.add("hello");
        bloomFilter.add("world");
        bloomFilter.add("guava");

        System.out.println(bloomFilter.mightContain("hello"));
        System.out.println(bloomFilter.mightContain("world"));
        System.out.println(bloomFilter.mightContain("gg"));
    }
}
